package com.xiaoxu.spzx.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.xiaoxu.spzx.model.entity.product.Category;
import com.xiaoxu.spzx.product.mapper.CategoryMapper;
import com.xiaoxu.spzx.product.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    //引入缓存Redis
    @Autowired
    private RedisTemplate<String,String>  redisTemplate;

    @Override
    public List<Category> selectOneCategory() {
        //1.查询Redis的数据 看是否存在品类的一级分类数据
        String jsonCategory = redisTemplate.opsForValue().get("category:one");

        if (StringUtils.hasText(jsonCategory)) {
            //2.将字符串类型转化为对象  不为空直接返回查询到的对象集合
            List<Category> existCategories = JSON.parseArray(jsonCategory, Category.class);
            return existCategories;
        }

        //3.如果没有查询数据库的数据
        List<Category> categoryList = categoryMapper.selectOneCategory();

        String categoryJsons = JSON.toJSONString(categoryList);

        //4.将数据库的数据添加到redis里面
        redisTemplate.opsForValue().set("category:one",categoryJsons,7, TimeUnit.DAYS);

        return   categoryList;
    }








    //查询所有的分类
    @Cacheable(value = "category" , key = "'all'")//开启缓存类似首页数据进入redis数据库
    @Override
    public List<Category> findCategoryTree() {
            List<Category> categoryList = categoryMapper.findAll();
            //全部一级分类
            List<Category> oneCategoryList = categoryList.stream().filter(item -> item.getParentId().longValue() == 0).collect(Collectors.toList());

            if(!CollectionUtils.isEmpty(oneCategoryList)) {
                oneCategoryList.forEach(oneCategory -> {
                    List<Category> twoCategoryList = categoryList.stream().filter(item -> item.getParentId().longValue() == oneCategory.getId().longValue()).collect(Collectors.toList());
                    oneCategory.setChildren(twoCategoryList);

                    if(!CollectionUtils.isEmpty(twoCategoryList)) {
                        twoCategoryList.forEach(twoCategory -> {
                            List<Category> threeCategoryList = categoryList.stream().filter(item -> item.getParentId().longValue() == twoCategory.getId().longValue()).collect(Collectors.toList());
                            twoCategory.setChildren(threeCategoryList);
                        });
                    }
                });
            }
            return oneCategoryList;
        }
}
